﻿// See https://aka.ms/new-console-template for more information
using JT809.DotNetty.Core;
using JT809.DotNetty.Core.Handlers;
using JT809.Protocol;
using JT809.Protocol.Configs;
using JT809.Superior.Server.Redis;
using JT809.Superior.Server.Redis.Configs;
using Microsoft.Extensions.DependencyInjection.Extensions;
using log4net.Config;
using Polly;
using SqlSugar.IOC;
using System.Runtime.InteropServices;
using SqlSugar;

//log4net
XmlConfigurator.Configure(LogHelper.Repository, new FileInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log4net.config")));

var builder = WebApplication.CreateBuilder(args);

//WindowService
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
    builder.Host.UseWindowsService();
}

//缓存
//builder.Services.AddMemoryCache();

//Redis
if (bool.TryParse(builder.Configuration.GetSection("Redis:Enabled").Value, out var redisEnabled))
{
    var _redisConnection = builder.Configuration.GetSection("Redis:Connection").Value;
    RedisHelper.Initialization(new CSRedis.CSRedisClient(_redisConnection));
}

////Sqlsugar
//builder.Services.AddSqlSugar(new IocConfig()
//{
//    ConfigId = "sql",
//    ConnectionString = builder.Configuration.GetConnectionString("sqlConnection"),
//    DbType = IocDbType.SqlServer,
//    IsAutoCloseConnection = true,//自动释放
//});

////配置参数
//SugarIocServices.ConfigurationSugar(db =>
//{
//    //db.Aop.OnLogExecuting = (sql, p) =>
//    //{
//    //    Console.WriteLine(sql);
//    //};

//    //设置更多连接参数
//    db.CurrentConnectionConfig.MoreSettings = new ConnMoreSettings() { PgSqlIsAutoToLower = false };
//});

//日志
builder.Services.AddLogging((logging) =>
{
    //Microsoft.Extensions.Logging.Console
    logging.AddConsole();
    //Microsoft.Extensions.Logging.Debug
    logging.AddDebug();
    //将LogInformation写入log4net中
    //要在log4netconfig中配置lockingModel为log4net.Appender.FileAppender+MinimalLock，否则会产生多个同名文件
    //logging.AddLog4Net();
});

builder.Services.AddSingleton(new JT809HeaderOptions
{
    EncryptFlag = JT809Header_Encrypt.None,
    Version = new JT809Header_Version(1, 0, 0),
    EncryptKey = 9595
});
builder.Services.AddJT809Configure()
        .AddJT809Core(builder.Configuration)
        .AddJT809SuperiorPlatform(options: options =>
        {
            options.TcpPort = int.TryParse(builder.Configuration.GetValue<string>("JT89GpsPort"), out int port) ? port : 17621;
        });
builder.Services.Configure<JT809GpsOptions>(builder.Configuration.GetSection("JT809GpsOptions"));
builder.Services.Replace(new ServiceDescriptor(typeof(JT809SuperiorMsgIdReceiveHandlerBase), typeof(JT809SuperiorMsgIdReceiveHandlerSimple), ServiceLifetime.Singleton));

var app = builder.Build();

app.Run();